package com.china08.yxyapi.service.mg.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.china08.yxyapi.entity.mg.scoreport.Exam;
import com.china08.yxyapi.entity.mg.scoreport.Exam.ExamQues;
import com.china08.yxyapi.entity.mg.scoreport.ExamStudent;
import com.china08.yxyapi.entity.mg.scoreport.ExamStudent.StuQuesScore;
import com.china08.yxyapi.entity.mg.scoreport.report.ExamQuesAnalyse;
import com.china08.yxyapi.entity.mg.scoreport.report.ExamQuesAnalyse.StudentScore;
import com.china08.yxyapi.entity.mg.scoreport.report.ExamQuesOverviewAnalyse;
import com.china08.yxyapi.repository.mg.scoreport.ExamQuesAnalyseRepsository;
import com.china08.yxyapi.repository.mg.scoreport.ExamQuesOverviewAnalyseRespository;
import com.china08.yxyapi.repository.mg.scoreport.ExamRepository;
import com.china08.yxyapi.repository.mg.scoreport.ExamStudentRepository;
import com.china08.yxyapi.service.mg.ExamQuesAnalyseService;
import com.china08.yxyapi.util.algorithm.ReportAlgorithm;
import com.china08.yxyapi.util.algorithm.ScoreAlgorithm;

@Service
public class ExamQuesAnalyseServiceImpl implements ExamQuesAnalyseService {

    @Autowired
    private ExamRepository examRepository;

    @Autowired
    private ExamStudentRepository examStudentRepository;

    @Autowired
    private ExamQuesOverviewAnalyseRespository examQuesOverviewAnalyseRespository;

    @Autowired
    private ExamQuesAnalyseRepsository examQuesAnalyseRepsository;

    // 小题简化分析
    @Override
    public void saveExamQuesOverviewAnalys(String examId) {
        BigDecimal bd = null;

        Exam exam = examRepository.findOne(examId);
        List<ExamStudent> examStu = examStudentRepository.findByExam(exam);

        ExamQuesOverviewAnalyse overviewAnalyse = null;

        overviewAnalyse = examQuesOverviewAnalyseRespository.findByExam(exam);

        if (overviewAnalyse == null) {
            overviewAnalyse = new ExamQuesOverviewAnalyse();
            // 考试对象
            overviewAnalyse.setExam(exam);
        }

        // 考试满分分数
        int examTotalScore = exam.getTotalScore();
        // 成绩集合
        List<Double> scoreLst = new ArrayList<>();
        for (ExamStudent examStudent : examStu) {
            scoreLst.add(examStudent.getStuTotalScore());
        }

        // 小题数量
        int quesNum = examStu.get(0).getStuQuesScores().size();
        overviewAnalyse.setQuesSum(quesNum);

        double obtainScoreAvgMax = 0d;
        List<Integer> orderNumLst = new ArrayList<Integer>();
        List<Double> obtainScoreAvgLst = new ArrayList<Double>();
        for (int i = 1; i <= quesNum; i++) {
            List<Double> quesLst = new ArrayList<Double>();
            int fullScore = 0;
            double obtainScoreAvg = 0d;
            for (ExamStudent examStudent : examStu) {
                for (StuQuesScore stuQues : examStudent.getStuQuesScores()) {
                    if (stuQues.order_num == i) {
                        quesLst.add(stuQues.stu_score);
                        fullScore = stuQues.score;
                        break;
                    }
                }
            }
            obtainScoreAvg = ReportAlgorithm.correct(quesLst, fullScore);
            if (obtainScoreAvg > obtainScoreAvgMax) {
                obtainScoreAvgMax = obtainScoreAvg;
                orderNumLst.clear();
                orderNumLst.add(i);
            } else if (obtainScoreAvg == obtainScoreAvgMax) {
                orderNumLst.add(i);
            }
            obtainScoreAvgLst.add(obtainScoreAvg);
        }
        // 题均失分率
        bd = new BigDecimal((1 - ScoreAlgorithm.scoreAvg(obtainScoreAvgLst)) * 100);
        overviewAnalyse.setLosePointRate(bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

        // 得分率最高的 题号
        List<String> maxScoreQues = new ArrayList<String>();
        for (ExamQues stuQues : exam.getQuestions()) {
            if (orderNumLst.contains(stuQues.order_num)) {
                if (StringUtils.isNotBlank(stuQues.noName)) {
                    maxScoreQues.add(stuQues.sectionName + "_" + stuQues.noName);
                } else {
                    maxScoreQues.add(stuQues.sectionName);
                }

            }
        }
        overviewAnalyse.setMaxScoreQues(StringUtils.join(maxScoreQues.toArray(), ","));

        // 本次卷面失分率
        bd = new BigDecimal((1 - ReportAlgorithm.correct(scoreLst, examTotalScore)) * 100);
        overviewAnalyse.setPaperLosePointRate(bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        examQuesOverviewAnalyseRespository.save(overviewAnalyse);
        saveExamQuesAnalyse(examId);
    }

    // 小题深度分析
    @Override
    public void saveExamQuesAnalyse(String examId) {
        BigDecimal bd = null;

        Exam exam = examRepository.findOne(examId);
        List<ExamStudent> examStu = examStudentRepository.findByExam(exam);

        for (ExamQues examQues : exam.getQuestions()) {

            ExamQuesAnalyse quesAnalyse = null;
            String id = exam.getId() + examQues.order_num;
            quesAnalyse = examQuesAnalyseRepsository.findOne(id);
            if (quesAnalyse == null) {
                quesAnalyse = new ExamQuesAnalyse();
                quesAnalyse.setId(id);
                quesAnalyse.setExam(exam);
            }

            // 大题号
            quesAnalyse.setSection(examQues.section);
            // 大题名称
            quesAnalyse.setSectionName(examQues.sectionName);
            // 小题号
            quesAnalyse.setNo(examQues.no);
            // 小题名称
            quesAnalyse.setNoName(examQues.noName);
            // 序列号
            quesAnalyse.setOrderNum(examQues.order_num);
            // 分数
            quesAnalyse.setScore(examQues.score);

            // 小题分数集合
            List<Double> quesScoreLst = new ArrayList<>();
            // 小题分数满分数据
            double quesFullScore = 0d;
            // 学生数据
            List<StudentScore> StudentScoreLst = new ArrayList<StudentScore>();

            for (ExamStudent examStudent : examStu) {
                for (StuQuesScore stuQues : examStudent.getStuQuesScores()) {
                    if (stuQues.order_num == examQues.order_num) {
                        quesScoreLst.add(stuQues.stu_score);
                        quesFullScore = stuQues.score;
                        StudentScore studentScore = quesAnalyse.new StudentScore();
                        studentScore.stu_id = examStudent.getStudentId();
                        studentScore.stu_nick = examStudent.getStudentNick();
                        studentScore.score = stuQues.stu_score;
                        StudentScoreLst.add(studentScore);
                    }
                }
            }

            // 正确率
            bd = new BigDecimal(ReportAlgorithm.correct(quesScoreLst, quesFullScore) * 100);
            quesAnalyse.setRightRate(bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            // 难度值
            double difficultyLevel = ReportAlgorithm.difficultyValue(quesScoreLst, quesFullScore);
            bd = new BigDecimal(difficultyLevel);
            quesAnalyse.setDifficultyLevel(bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            // 当前最大的波动度
            List<Double> waveLevelMaxLst = new ArrayList<>();
            waveLevelMaxLst.add(0d);
            waveLevelMaxLst.add(quesFullScore);
            double waveLevelMax = ReportAlgorithm.volatilityValue(waveLevelMaxLst);
            // 波动度
            double waveLevel = ReportAlgorithm.volatilityValue(quesScoreLst);
            bd = new BigDecimal(waveLevel);
            quesAnalyse.setWaveLevel(bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            // 区分度
            double differentiationValue = ReportAlgorithm.differentiationValue(quesScoreLst, quesFullScore);
            // 学生名单
            StudentScoreLst.sort((StudentScore h1, StudentScore h2) -> h2.score.compareTo(h1.score));
            quesAnalyse.setStudentScore(StudentScoreLst);

            // 详细分析
            String remark = "";
            // 难度分析
            if (difficultyLevel >= 0.6) {
                remark += "本题目从本班考试成绩来看有些简单,";
            } else if (difficultyLevel >= 0.2 && difficultyLevel < 0.6) {
                remark += "本题目从本班考试成绩来看难度适当,";
            } else if (difficultyLevel < 0.2) {
                remark += "本题目从本班考试成绩来看难度较大,";
            }
            // 波动度分析
            if (waveLevel >= waveLevelMax * 0.6) {
                remark += "当前班级波动度很大，班级成绩两极化趋势明显,";
            } else if (waveLevel > waveLevelMax * 0.4) {
                remark += "当前班级波动度略大，班级成绩有两极化趋势,";
            } else if (waveLevel <= waveLevelMax * 0.4) {
                remark += "当前成绩波动度稳定，班级成绩,";
            }
            // 区分度分析
            if (differentiationValue >= 0.4) {
                remark += "当前题目对学生考核的区分度非常好.";
            } else if (differentiationValue >= 0.3 && differentiationValue < 0.4) {
                remark += "当期对学生考核的区分度良好.";
            } else if (differentiationValue >= 0.2 && differentiationValue < 0.3) {
                remark += "当期对学生考核的区分一般题目需要改进.";
            } else if (differentiationValue < 0.2) {
                remark += "当期对学生考核的区分度较差，下次需要淘汰本类试题.";
            }
            quesAnalyse.setRemark(remark);
            examQuesAnalyseRepsository.save(quesAnalyse);
        }

    }

}
